package com.lge.clock.timer;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnKeyListener;
import android.database.Cursor;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
// [suhyun99.kim][1433] 2011.10.13 
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.format.DateFormat;

import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lge.clock.R;
import com.lge.clock.TimerFragment;
import com.lge.clock.alarmclock.Alarms;
import com.lge.clock.alarmclock.PouchMode;
import com.lge.clock.alarmclock.SettingsActivity;
import com.lge.clock.util.CommonUtil;
import com.lge.clock.util.CommonUtil.CallStateHolder;

/**
 * @author LGE Cappuccino
 */
public class TimerFullDialog extends Activity {
	private static final int AUTO_TIMER_OUT = 1001;
	//private static final String SCREEN_OFF = "screen_off";
	private static final String TAG = "TimerFullDialog";
	private static final int KEYCODE_3DCAMERA = 92;
	private AlertDialog ad = null;
	private TelephonyManager mTelephonyManager;
	
	private CallStateHolder mInitialCallState;
	private AudioManager mAudioManager = null;
//	private boolean mPlayingMusic = false;
	// [suhyun99.kim][1402] 2011.10.13.
	private boolean mTimeIs = false;
	// [minjoong.park][1398] 2011.10.15. START
    private boolean mPouch = false;
    static int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
	// [minjoong.park][1398] 2011.10.15. END
    
    //[suhaeng.lee][2884] 2012.01.03 START
    private static final String TIMER_RUNNING = "running";
    //[suhaeng.lee][2884] 2012.01.03 END
    
    private static final String M12 = "h:mm";
	private static final String M24 = "kk:mm";
	 
	private Calendar mCalendar;
	private String mFormat;
	private TextView dateString;//, AMText, PMText;
	
	private final String[] mNumDigitDrawables = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
	
//	private boolean koreaYN = false;
	
	private static final int NO_CHARGE = 0;
	private int mBatteryLevel = 100;
	private int mIsBatteryCharging = NO_CHARGE; // 0 means it is on battery, other constants are different types of power sources.

    private String mStrTimerTime ="0";
    
	private final Handler mSoundHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case AUTO_TIMER_OUT:
					// [suhyun99.kim][1402] 2011.10.13.
					mTimeIs = true;
					finish();
					
				default :
					break;
			}
		}
	};

	private final PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
		@Override
		public void onCallStateChanged(int state, String ignored) {
			if (state != TelephonyManager.CALL_STATE_IDLE && mInitialCallState.equals(CommonUtil.getNowCallState(getApplicationContext(), mTelephonyManager)) == false ) {
				
				////[suhaeng.lee][1394] 2011.10.10. START
	            ////////////Notification above Timer bottom Time is up and currenttime///////////
				Calendar cal = Calendar.getInstance();
	        	cal.setTimeInMillis(System.currentTimeMillis());
	        	boolean is24Hours = android.text.format.DateFormat.is24HourFormat(TimerFullDialog.this);
	        	String format = is24Hours ? "kk:mm" : "hh:mm AA";
	        	String timeText = " ("+(String)DateFormat.format(format, cal)+")";  
				
	        	NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
	        	nm.cancel(1);
	    		Notification noti = new Notification(R.drawable.stat_notify_alarm, getText(R.string.superclock_timer).toString(), System.currentTimeMillis());
	    		noti.flags |= Notification.FLAG_AUTO_CANCEL;
	    		noti.flags |= Notification.FLAG_SHOW_LIGHTS;
	    		noti.flags |= Notification.DEFAULT_LIGHTS;
//	    		noti.ledARGB = 0xFF00FF00;
//	    		noti.ledOnMS = 500;
//	    		noti.ledOffMS = 500;
	    		PendingIntent contentIntent = PendingIntent.getActivity(TimerFullDialog.this, 0, new Intent(), 0);
	    		noti.setLatestEventInfo(TimerFullDialog.this, getText(R.string.superclock_timer).toString(), getText(R.string.timer_done).toString() + timeText, contentIntent);
	    		nm.notify(1, noti);
	    		////////////Notification above Timer bottom Time is up and currenttime///////////
	    		//[suhaeng.lee][1394] 2011.10.10. END
				
				finish();
			}
		}
	};

	/**
	 * Method onCreate.
	 * @param savedInstanceState Bundle
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "[onCreate]");
		
		//[suhaeng.lee][2884] 2012.01.03 START
		mSharedPreferences = getSharedPreferences("TIMER_STATE", 0);
		mEditor = mSharedPreferences.edit();
		
		Log.d(TAG, "timer running is = true");
		mEditor.putBoolean(TIMER_RUNNING, true);
		mEditor.commit();
		//[suhaeng.lee][2884] 2012.01.03 END
		
		
		requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);
		
		
		mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
		if("Off".equalsIgnoreCase(loadTonePreferences()) == false && !silenceModeChecking()) {
	        mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
		} else {
			mAudioManager = null;
		}
 //       mPlayingMusic = mAudioManager.isMusicActive();

		final Window win = getWindow();
		// [suhyun99.kim][1399] 2011.10.11. START
		win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
				//| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
		// [suhyun99.kim][1399] 2011.10.11. END
		Intent closeDialogs = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
		sendBroadcast(closeDialogs);
		mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
		mInitialCallState = CommonUtil.getNowCallState(this, mTelephonyManager);
		
//		Log.d(TAG,"TimerFullDialog onCreate sendBroadcast [Play Pause]");
//		Intent music = new Intent("com.android.music.musicservicecommand");
//		music.putExtra("command", "toggleplay");
//		music.putExtra("status", "start");
//		sendBroadcast(music);
		
		// [start][yeonju7.kim][P940] 2011.09.21 ADD Fm Radio intent "status"  
//        Log.d(TAG, "TimerFullDialog onCreate sendBroadCast [FmRadio pause]");
//        Intent fmRadio = new Intent("com.ti.server.fmresumecmd");
//        fmRadio.putExtra("status", "start");
//        sendBroadcast(fmRadio);
        // [end][yeonju7.kim][P940] 2011.09.21 ADD Fm Radio intent "status"  

		win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
				| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
				| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
		// [minjoong.park][1398] 2011.10.15. START
        
	}

	private void setTimerTime(){
		int time = mSharedPreferences.getInt(TimerFragment.SETTIME, 0);
		mStrTimerTime = CommonUtil.formatTotalTime(time);		
	}
	
	private void updateLayout() {
		LayoutInflater inflater = LayoutInflater.from(this);
		setContentView(inflateView(inflater));

		if(ad != null){
			ad.dismiss();
		}
		
		try {
			Intent playTimer = new Intent(this, TimerAlarm.class);
			mSharedPreferences = getSharedPreferences("TIMER_STATE", 0);
			playTimer.putExtra("Vibration", loadVibPreferences());
			playTimer.putExtra("Ringtone", loadTonePreferences());
			setTimerTime();
			startService(playTimer);
		} catch(NullPointerException e) {
			e.printStackTrace();
		}

		//sendBroadcast(timerKilled);
		/*[START] 2012.04.04 suein1209.kim*/
//		if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
		/*[END] 2012.04.04 suein1209.kim*/
		if (CommonUtil.isCallStateIdle(mTelephonyManager, getApplicationContext()) == false) {
			Toast.makeText(this, R.string.timer_done, Toast.LENGTH_SHORT).show();
			finish();
		}
		else {
			if (!mPouch) {
				this.setContentView(R.layout.timerdialog);
				mSoundHandler.sendMessageDelayed(mSoundHandler.obtainMessage(AUTO_TIMER_OUT), 1000 * 180 * 1);
				
		        View alarmTime = inflater.inflate(R.layout.timer_dialog_time, (ViewGroup)findViewById(R.id.alarmdialog));
		        ((TextView)alarmTime.findViewById(R.id.dialog_hour_Text01)).setText(mStrTimerTime);
		        
				// [minjoong.park][1398] 2011.10.15. START
				ad = new AlertDialog.Builder(this)
				.setIconAttribute(android.R.attr.alertDialogIcon)
				.setTitle(R.string.timer_done).setView(alarmTime)
				.setPositiveButton(R.string.sp_stop_name_NORMAL,//P930_TD#15368_20110719 Dismiss -> Stop 
						//.setPositiveButton(R.string.dismiss,//P930_TD#15368_20110719 Dismiss -> Stop 
						new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int which) {
						finish();
					}
				}).setOnKeyListener(new OnKeyListener() {

					public boolean onKey(DialogInterface dialog,
							int keyCode, KeyEvent event) {

						
						switch (keyCode) {
							case KeyEvent.KEYCODE_VOLUME_UP:
							case KeyEvent.KEYCODE_VOLUME_DOWN:
							case KEYCODE_3DCAMERA:
								if(event.getAction() == KeyEvent.ACTION_UP ) {
									finish();
								}
								return true;
								
							case KeyEvent.KEYCODE_BACK :
							case KeyEvent.KEYCODE_MENU :
							case KeyEvent.KEYCODE_SEARCH :
								return true;
						}
				
						return false;
					}

				}).create();

				//[suhaeng.lee][2294] 2011.12.14 START
				ad.setCanceledOnTouchOutside(false);
				//[suhaeng.lee][2294] 2011.12.14 END

				ad.show();
				// [minjoong.park][1398] 2011.10.15. END

			}
			else {
				time_init();

				TextView batteryCharging;
				TextView batteryChargingBackground;

				batteryCharging = (TextView)findViewById(R.id.batteryCharging);
				batteryChargingBackground= (TextView)findViewById(R.id.batteryChargingBackground);

				if (mIsBatteryCharging == NO_CHARGE) {
					batteryCharging.setVisibility(View.GONE);
					batteryChargingBackground.setVisibility(View.GONE);
				}
				else {
					batteryCharging.setText(getResources().getString(R.string.sp_battery_info_status_charging_NORMAL)+" (" + mBatteryLevel + "%)");
				}
			}
		}
	}

    protected View inflateView(LayoutInflater inflater) {
    	return inflater.inflate(R.layout.timer_alert_pouch, null);
    }
    
	/**
	 * Method onResume.
	 */
	@Override
	protected void onResume() {
		super.onResume();

		Log.d(TAG, "[onResume]");
		// [minjoong.park][1398] 2011.10.15. START
		IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_DOCK_EVENT);
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        filter.addAction(Alarms.ALARM_ALERT_ACTION);
        registerReceiver(timerIntentReceiver, filter, null, mHandler);
		// [minjoong.park][1398] 2011.10.15. END
        
        updateLayout();
	}
	
	// [minjoong.park][1398] 2011.10.15. START
	private final Handler mHandler = new Handler();
	
	private final BroadcastReceiver timerIntentReceiver = new BroadcastReceiver() {
    	@Override
        public void onReceive(Context context, Intent intent) {
    	    Log.e(TAG, "intent.getAction() => " + intent.getAction());
    	    if(Alarms.ALARM_ALERT_ACTION.equals(intent.getAction())){    	    	
    	    	mSoundHandler.sendMessage(mSoundHandler.obtainMessage(AUTO_TIMER_OUT));
    	    	return;
    	    }
    	    
    	    if (Intent.ACTION_DOCK_EVENT.equals(intent.getAction())) {
    	    	boolean oldMPouch = mPouch;
    	    	mPouch = PouchMode.getDockState(intent);

    	    	if (oldMPouch == true && mPouch == false) {
    	    		finish();
    	    		return;
    	    	}
    	    }
    	    else if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
    	    	Log.e(TAG, "Battery : " + intent.getIntExtra("level", -1)+ "%" );
    	    	mIsBatteryCharging = intent.getIntExtra("plugged", 0);
    	    	mBatteryLevel = intent.getIntExtra("level", 100);
    	    }
    	    else if (Intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
    	    	mCalendar = Calendar.getInstance();
    	    	if (mPouch) {
    	    		updateTime();
    	    	}
    	    }

    	    if (mPouch) {
    	    	updateLayout();
    	    }
        }    
    };
    // [minjoong.park][1398] 2011.10.15. END

	/**
	 * Method finish.
	 */
	@Override
	public void finish() {
		super.finish();
		
		//[suhaeng.lee][2884] 2012.01.03 START
		Log.d(TAG, "timer running is = false");
		mEditor.putBoolean(TIMER_RUNNING, false);
		mEditor.commit();
		//[suhaeng.lee][2884] 2012.01.03 END
		
		Log.d(TAG, "[Finish]");
		//[mo2sangbong.lee][1665] 2011.11.04 START
		mSoundHandler.removeMessages(AUTO_TIMER_OUT);
		//[mo2sangbong.lee][1665] 2011.11.04 END
		// [suhyun99.kim][1402] 2011.10.13. START
		if(mTimeIs){
			NotificationManager nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
	        nm.cancel(1);
	    	Notification noti = new Notification(R.drawable.stat_notify_alarm, this.getText(R.string.superclock_timer).toString(), System.currentTimeMillis());
	    	noti.flags |= Notification.FLAG_AUTO_CANCEL;
	        noti.flags |= Notification.FLAG_SHOW_LIGHTS;
	        noti.flags |= Notification.DEFAULT_LIGHTS;
//	        noti.ledARGB = 0xFF00FF00;
//	        noti.ledOnMS = 500;
//	        noti.ledOffMS = 500;
	    	PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(), 0);
	    	noti.setLatestEventInfo(this, this.getText(R.string.superclock_timer).toString(), this.getText(R.string.timer_done).toString(), contentIntent);
	    	nm.notify(1, noti);
		}
		// [suhyun99.kim][1402] 2011.10.13. END
		stopService(new Intent(this, TimerAlarm.class));
		mTelephonyManager.listen(mPhoneStateListener, 0);
		
		//[mo2sangbong.lee][1817] 2011.11.11 START
		if (timerIntentReceiver != null) {
			try{
				unregisterReceiver(timerIntentReceiver);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
				//[mo2sangbong.lee][1817] 2011.11.11 END
			
//		Log.d(TAG,"TimerFullDialog finish sendBroadCast [Music Restart]");
//		Intent music = new Intent("com.android.music.musicservicecommand");
//		music.putExtra("command", "toggleplay");
//		music.putExtra("status", "end");
//		sendBroadcast(music);
			
		// [start][yeonju7.kim][P940] 2011.09.21 ADD Fm Radio intent "status"  
//	    Log.d(TAG, "TimerFullDialog finish sendBroadCast [FmRadio Restart]");
//	    Intent fmRadio = new Intent("com.ti.server.fmresumecmd");
//	    fmRadio.putExtra("status", "end");
//	    sendBroadcast(fmRadio);
	    // [end][yeonju7.kim][P940] 2011.09.21 ADD Fm Radio intent "status"
	    
	    //[suhaeng.lee][2258] 2011.12.14 START
	    Intent timerKilled = new Intent("com.android.clock.timer.timer_killed");
	    sendBroadcast(timerKilled);
		//[suhaeng.lee][2258] 2011.12.14 END
	    
		TimerFragment.releaseLocks();
	}

	/**
	 * Method onPause.
	 */
	@Override
	protected void onPause() {
		super.onPause();
		Log.d(TAG, "[onPause]");
		
//		// [suhyun99.kim][1433] 2011.10.13. START
//		if ((mAudioManager != null) && (mAudioFocusListener != null)){
//			mAudioManager.abandonAudioFocus(mAudioFocusListener);
//		}		
//		// [suhyun99.kim][1433] 2011.10.13. END		
//		
	}

	/**
	 * Method onStop.
	 */
	@Override
	protected void onStop() {
		super.onStop();
		Log.d(TAG, "[onStop]");
		if(ad!= null){
			ad.dismiss();
		}	
		// [suhyun99.kim][1433] 2011.10.13. START
		if ((mAudioManager != null) && (mAudioFocusListener != null)) {
			mAudioManager.abandonAudioFocus(mAudioFocusListener);
		}
		// [suhyun99.kim][1433] 2011.10.13. END
		finish();
	}

	/**
	 * Method onDestroy.
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "timerdialog[onDestroy]");
	}

	/**
	 * Method dispatchKeyEvent.
	 * @param event KeyEvent
	 * @return boolean
	 * @see android.view.Window$Callback#dispatchKeyEvent(KeyEvent)
	 */
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		return super.dispatchKeyEvent(event);
	}
	
	private static final String VIBRATION = "vibration";
	private static final String RINGTONE = "rintone";
	private static SharedPreferences mSharedPreferences;
	private static SharedPreferences.Editor mEditor;
	private boolean loadVibPreferences()
	{
		return mSharedPreferences.getBoolean(VIBRATION, true);
	}
	
	private String loadTonePreferences()
	{
		return mSharedPreferences.getString(RINGTONE, defaultRingtone());
	}

	private static final String[] INTERNAL_COLUMNS = new String[] {
		android.provider.BaseColumns._ID, 
		android.provider.MediaStore.MediaColumns.TITLE,
		"\"" + MediaStore.Audio.Media.INTERNAL_CONTENT_URI + "\"",
		android.provider.MediaStore.Audio.AudioColumns.TITLE_KEY
	};
	
	private String defaultRingtone() {
		String defaultTone = "";
	    Uri alert = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
	    
		if (alert == null) {
			defaultTone	= "Off";
			return defaultTone;
		}
		
	    ContentResolver resolver = this.getContentResolver();
	    
	    Cursor cur = null;
        try {
			cur = resolver.query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, INTERNAL_COLUMNS,
							               "is_alarm = 1",  null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER); 
			
			String temp = defaultRingtoneTitle();
			Log.d(TAG, "=>" + temp + "<=" );
			
			if (cur != null && cur.moveToFirst()) {
				do {
					Uri uri1 = ContentUris.withAppendedId(Uri.parse(cur.getString(2)), cur.getLong(0));
			        int aa = (cur.getString(1)).indexOf( temp );
			        if ( aa >=0 ) {
			        	Log.d(TAG, temp + " / Title=" +  cur.getString(1)  +   "<==  URI ==>" + uri1.toString() ) ;
			        	defaultTone	=	uri1.toString() ;	
			        	break;
			        }
			          
				} while (cur.moveToNext());
			}         
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if ( cur != null )
				cur.close();
		}
	 	
	 	if ("".equals(defaultTone.trim())) {
	 		defaultTone	= "Off";  
	 	}
	 	      
	 	Log.d(TAG, "====defaultTone======>" +  defaultTone );
	 	return defaultTone ;
	}
      
    private String defaultRingtoneTitle() {
    	Uri alert = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
	    
    	if (alert != null) {
    		final Ringtone r = RingtoneManager.getRingtone(this, alert);
    		if (r != null) {
    			Log.d(TAG, "=default===> " + r.getTitle(this)  );
    			return r.getTitle(this);  
    		}
    	}
    	
    	return "" ;
    }	
	// [suhyun99.kim][1433] 2011.10.13. START
	private OnAudioFocusChangeListener mAudioFocusListener = new OnAudioFocusChangeListener() {
        public void onAudioFocusChange(int focusChange) {
            // AudioFocus is a new feature: focus updates are made verbose on purpose
            switch (focusChange) {
                case AudioManager.AUDIOFOCUS_LOSS:
                    Log.d(TAG, "Timer AudioFocus: received AUDIOFOCUS_LOSS");
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    Log.d(TAG, "Timer AudioFocus: received AUDIOFOCUS_LOSS_TRANSIENT");
                    break;
                case AudioManager.AUDIOFOCUS_GAIN:
                    Log.d(TAG, "Timer AudioFocus: received AUDIOFOCUS_GAIN");
                    break;
                default:
                    Log.e(TAG, "Timer Unknown audio focus change code");
            }
        }
	};    
	// [suhyun99.kim][1433] 2011.10.13. END
	
	private boolean silenceModeChecking() {
		
		if( "Off".equalsIgnoreCase(loadTonePreferences()))
			return true;
		
		boolean bResult = false;
		Log.d(TAG, "silenceModeChecking()");    
		int getRingerMode = 0;
		final String modeRinger = "mode_ringer";
		  
		ContentResolver mContentResolver = getContentResolver();
		if( mAudioManager == null ) {
			mAudioManager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
			getRingerMode = android.provider.Settings.System.getInt(mContentResolver, modeRinger, AudioManager.RINGER_MODE_NORMAL);
		}
		else {
			getRingerMode = mAudioManager.getRingerMode();
		}
		 
		String setSoundButton = "";
		switch( getRingerMode )
		{
			case AudioManager.RINGER_MODE_NORMAL:
				setSoundButton = "ON";
				break;
			case AudioManager.RINGER_MODE_SILENT:
			case AudioManager.RINGER_MODE_VIBRATE:
				Log.d(TAG, "setSoundButton: Sound Silent");
				setSoundButton = "Silent";
				break;
			default :
				break;
		}
		      
        final int silentModeStreams = Settings.System.getInt(getContentResolver(),
        			Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
       
        boolean silenceYN = false;
       
        if( (silentModeStreams & SettingsActivity.ALARM_STREAM_TYPE_BIT) == 0 )
        	silenceYN = true;
       
        Log.d(TAG,"===setSoundButton===" + setSoundButton + "==silenceYN===" + silenceYN);
                  
	    if ("Silent".equalsIgnoreCase(setSoundButton) &&  silenceYN == false) {
	    	Log.d(TAG, "==========(Silence mode even if Alarm fire)================");
	    	bResult = true;
	    }
    	
	    return bResult;
	}	
	
	public void time_init() {        
        dateString = (TextView)findViewById(R.id.dateString);
        mCalendar = Calendar.getInstance();
        mFormat = is24HourMode(this) ? M24 : M12;

        updateTime();
    }   
	
	private static boolean is24HourMode(final Context context) {
        return android.text.format.DateFormat.is24HourFormat(context);
    } 
	
	private void updateTime() {
		TextView apm;
		TextView mHour01;
		TextView mHour02;
		TextView mMinute01;
		TextView mMinute02;

		mCalendar.setTimeInMillis(System.currentTimeMillis());
		int minutes = mCalendar.get(Calendar.MINUTE);
		int hour    = mCalendar.get(Calendar.HOUR);

		String[] strMONTH = {
				getResources().getString(R.string.sp_january_SHORT), 
				getResources().getString(R.string.sp_February_SHORT), 
				getResources().getString(R.string.sp_march_SHORT),
				getResources().getString(R.string.sp_april_SHORT),
				getResources().getString(R.string.sp_may_SHORT),
				getResources().getString(R.string.sp_june_SHORT),
				getResources().getString(R.string.sp_july_SHORT),
				getResources().getString(R.string.sp_august_SHORT),
				getResources().getString(R.string.sp_september_SHORT),
				getResources().getString(R.string.sp_october_SHORT),
				getResources().getString(R.string.sp_november_SHORT),
				getResources().getString(R.string.sp_december_SHORT)};

		String[] yoil = {"", 
	    		getResources().getString(R.string.sp_sunday_NORMAL),
	    		getResources().getString(R.string.sp_monday_NORMAL),
	    		getResources().getString(R.string.sp_tuesday_NORMAL),
	    		getResources().getString(R.string.sp_wednesday_NORMAL),
	    		getResources().getString(R.string.sp_thursday_NORMAL),
	    		getResources().getString(R.string.sp_friday_NORMAL),
	    		getResources().getString(R.string.sp_saturday_NORMAL)};

		boolean is24HourFormat = DateFormat.is24HourFormat(this) ;  
		Log.d(TAG, "===updateTime===> " +  hour + " / " + minutes) ;          		
		//////////////////////////////////////////////////////////////////////////////
		if (is24HourFormat == true) {
			Log.d(TAG, "==========24 mode==============") ;

			findViewById(R.id.apm_ID).setVisibility(View.GONE);
			findViewById(R.id.timer_alert).setPadding(0, 0, 0, 0);
			findViewById(R.id.timer_stop_icon).setPadding(-4, 0, 0, 0);

			if (mCalendar.get(Calendar.AM_PM) == 1) {
				hour += 12 ;
			} 
		}    

		if (is24HourFormat == false){
			Log.d(TAG, "==========am/pm mode==============>>> " +  mCalendar.get(Calendar.AM_PM) ) ;
			if ( mCalendar.get(Calendar.AM_PM) == 0 ) {
				apm = (TextView)findViewById(R.id.apm_ID);
				apm.setText(R.string.sp_AM_string_NORMAL);
			}
			else {
				apm = (TextView)findViewById(R.id.apm_ID);
				apm.setText(R.string.sp_PM_string_NORMAL);
			}

			if (hour == 0) {
				hour = 12;
			}
		}

		int digit1 = hour / 10;
		int digit0 = hour % 10;
		//		Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),
		//        "fonts/Clockopia.ttf");
		mHour01 = (TextView)findViewById(R.id.hour_Text01);
		mHour01.setText(mNumDigitDrawables[digit1]);
		if (is24HourFormat == false && digit1 == 0) {
		    mHour01.setVisibility(View.GONE);
			findViewById(R.id.timer_stop_icon).setPadding(18, 0, 0, 0);
	        }
		mHour02 = (TextView)findViewById(R.id.hour_Text02);
		mHour02.setText(mNumDigitDrawables[digit0]);
		//		mHour01.setTypeface(tf);
		//		mHour02.setTypeface(tf);

		////////////////////////////////////////////////////////////////////////////////////////

		int mdigit1 = minutes / 10;
		int mdigit0 = minutes % 10;   

		mMinute01 = (TextView)findViewById(R.id.min_Text01);
		mMinute01.setText(mNumDigitDrawables[mdigit1]);
		mMinute02 = (TextView)findViewById(R.id.min_Text02);
		mMinute02.setText(mNumDigitDrawables[mdigit0]);
		//		mMinute01.setTypeface(tf);
		//		mMinute02.setTypeface(tf);

		//////////////////////////////////////////////////////////////////////////////////////////////

		String dateStringTemp;

		dateStringTemp = yoil[mCalendar.get(Calendar.DAY_OF_WEEK)] + ", " 
				+ strMONTH[mCalendar.get(Calendar.MONTH)] + " " 
				+ mCalendar.get(Calendar.DATE);

		/*[START] 2012.03.14 suein1209.kim change the display time type in Japan lang*/
        if (CommonUtil.isAsiaLanguage(this)) {
        	String dateStringkor = (mCalendar.get(Calendar.MONTH)+1) + "/" + mCalendar.get(Calendar.DATE) +  " (" + yoil[mCalendar.get(Calendar.DAY_OF_WEEK)] + ")";
        	dateString.setText(dateStringkor);
  
        } else {
        	dateString.setText( dateStringTemp );
        }
        /*[END] 2012.03.14 suein1209.kim change the display time type in Japan lang*/
		
	}

//	private boolean isKoreaChinaTaiwan(){
//
//		boolean bResult = false;
//		String language = this.getResources().getConfiguration().locale.getCountry();
//		if("KR".equalsIgnoreCase(language) ||
//				"CN".equalsIgnoreCase(language) ||
//				"TW".equalsIgnoreCase(language)){
//			bResult = true;
//		}
//		return bResult;
//	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (mPouch) {
			switch (keyCode) {
			case KeyEvent.KEYCODE_VOLUME_UP:
				finish();
				return true;
			case KeyEvent.KEYCODE_VOLUME_DOWN:
				finish();
				return true;
			}
		}
		// TODO Auto-generated method stub
		return super.onKeyDown(keyCode, event);
	}
}
